package com.yizhilu.os.edu.controller.kuaijidao;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yizhilu.os.common.constants.CommonConstants;
import com.yizhilu.os.common.constants.MemConstans;
import com.yizhilu.os.common.contoller.SingletonLoginUtils;
import com.yizhilu.os.common.util.MobileMessageSendUtil;
import com.yizhilu.os.core.entity.PageEntity;
import com.yizhilu.os.core.service.cache.MemCache;
import com.yizhilu.os.core.service.email.EmailService;
import com.yizhilu.os.core.util.ObjectUtils;
import com.yizhilu.os.core.util.PreventInfusion;
import com.yizhilu.os.core.util.Security.PurseSecurityUtils;
import com.yizhilu.os.core.util.StringUtils;
import com.yizhilu.os.core.util.web.WebUtils;
import com.yizhilu.os.edu.common.EduBaseController;
import com.yizhilu.os.edu.constants.enums.CourseProfileType;
import com.yizhilu.os.edu.constants.enums.ImagesType;
import com.yizhilu.os.edu.constants.enums.IntegralKeyword;
import com.yizhilu.os.edu.constants.enums.SellType;
import com.yizhilu.os.edu.constants.enums.UserExpandFrom;
import com.yizhilu.os.edu.constants.enums.WebSiteProfileType;
import com.yizhilu.os.edu.constants.web.SnsConstants;
import com.yizhilu.os.edu.entity.answer.AnswerQuestion;
import com.yizhilu.os.edu.entity.article.Article;
import com.yizhilu.os.edu.entity.course.CourseDto;
import com.yizhilu.os.edu.entity.course.CourseProfile;
import com.yizhilu.os.edu.entity.letter.MsgReceive;
import com.yizhilu.os.edu.entity.letter.QueryMsgReceive;
import com.yizhilu.os.edu.entity.member.MemberRecordDTO;
import com.yizhilu.os.edu.entity.order.QueryTrxorder;
import com.yizhilu.os.edu.entity.user.QueryUserAccounthistory;
import com.yizhilu.os.edu.entity.user.User;
import com.yizhilu.os.edu.entity.user.UserAccount;
import com.yizhilu.os.edu.entity.user.UserAccounthistory;
import com.yizhilu.os.edu.entity.user.UserCode;
import com.yizhilu.os.edu.entity.user.UserExpand;
import com.yizhilu.os.edu.entity.user.UserExpandDto;
import com.yizhilu.os.edu.entity.user.UserForm;
import com.yizhilu.os.edu.entity.userprofile.UserProfile;
import com.yizhilu.os.edu.entity.website.WebsiteImages;
import com.yizhilu.os.edu.entity.website.WebsiteProfile;
import com.yizhilu.os.edu.service.answer.AnswerQuestionService;
import com.yizhilu.os.edu.service.article.ArticleService;
import com.yizhilu.os.edu.service.course.CourseService;
import com.yizhilu.os.edu.service.kuaijidao.UserKuaijiDaoService;
import com.yizhilu.os.edu.service.letter.MsgReceiveService;
import com.yizhilu.os.edu.service.member.MemberRecordService;
import com.yizhilu.os.edu.service.order.TrxorderDetailService;
import com.yizhilu.os.edu.service.order.TrxorderService;
import com.yizhilu.os.edu.service.user.LoginOnlineService;
import com.yizhilu.os.edu.service.user.UserAccountService;
import com.yizhilu.os.edu.service.user.UserAccounthistoryService;
import com.yizhilu.os.edu.service.user.UserCodeService;
import com.yizhilu.os.edu.service.user.UserExpandService;
import com.yizhilu.os.edu.service.user.UserIntegralService;
import com.yizhilu.os.edu.service.user.UserService;
import com.yizhilu.os.edu.service.userprofile.UserProfileService;
import com.yizhilu.os.edu.service.website.WebsiteImagesService;
import com.yizhilu.os.edu.service.website.WebsiteProfileService;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.yizhilu.os.common.util.SystemUtil;

@Controller
@RequestMapping({"/kuaijidao"})
public class UserH5Controller extends EduBaseController
{
  private Logger logger = LoggerFactory.getLogger(UserH5Controller.class);
  @Autowired
  private UserService userService;
  @Autowired
  private UserExpandService userExpandService;
  @Autowired
  private UserCodeService userCodeService;
  @Autowired
  private EmailService emailService;
  @Autowired
  private CourseService courseService;
  @Autowired
  private ArticleService articleService;
  @Autowired
  private UserIntegralService userIntegralService;
  @Autowired
  private UserAccountService userAccountService;
  @Autowired
  private UserAccounthistoryService userAccounthistoryService;
  @Autowired
  private MsgReceiveService msgReceiveService;
  @Autowired
  private WebsiteImagesService websiteImagesService;
  @Autowired
  private MemberRecordService memberRecordService;
  @Autowired
  private LoginOnlineService loginOnliceService;
  @Autowired
  private WebsiteProfileService websiteProfileService;
  @Autowired
  private AnswerQuestionService answerQuestionService;
  @Autowired
  private UserProfileService userProfileService;
  
  @Autowired
  TrxorderDetailService trxorderDetailService;
  
  @Autowired
  private TrxorderService trxorderService;
  
  
  @Autowired
  private UserKuaijiDaoService userKuaijiDaoService;
  
  MemCache memCache = MemCache.getInstance();
  private String toUpdatePwd = getViewPath("/user/change_password");
  private String registerJsp = getViewPath("/user/register");
  private String loginjsp = getViewPath("/user/login");
  private String forgetpwdjsp = getViewPath("/user/forgetpwd");
  private String getpwdjsp = getViewPath("/user/getpwd");
  private String uc_home = getViewPath("/ucenter/uchome");
  private String toPwd = getViewPath("/ucenter/update_pwd");
  private String userInfo = getViewPath("/ucenter/user_info");
  private String avatar = getViewPath("/ucenter/avatar");
  private String accoutList = getViewPath("/ucenter/account_list");
  private String memberInfo = getViewPath("/ucenter/member_info");
  private String queryUserLetter = getViewPath("/ucenter/u_letter_inbox");
  private String toMyCouAnswerQuestion = getViewPath("/ucenter/myAnswer");
  private String ucinfo = getViewPath("/uc/uinfo");
  
  @InitBinder({"userForm"})
  public void initBinder1(WebDataBinder binder)
  {
    binder.setFieldDefaultPrefix("userForm.");
  }
  
  @InitBinder({"queryUser"})
  public void initBinderqueryUser(WebDataBinder binder)
  {
    binder.setFieldDefaultPrefix("queryUser.");
  }
  
  @InitBinder({"msgReceive"})
  public void initBinderMsgReceive(WebDataBinder binder)
  {
    binder.setFieldDefaultPrefix("msgReceive.");
  }
  
  @RequestMapping({"/register"})
  public String regist()
  {
    return this.loginjsp;
  }
  
  @RequestMapping({"/front/forget_passwd"})
  public String forgotpwd()
  {
    return this.forgetpwdjsp;
  }
  
  @RequestMapping({"/login"})
  public String toIndex()
  {
    return this.loginjsp;
  }
  
  @RequestMapping({"/toUpdatePwd"})
  public String toUpdatePwd()
  {
    return this.toUpdatePwd;
  }
  
  @RequestMapping({"/limitVerifyError"})
  public String limitVerifyError()
  {
    return "/admin/login/limitVerifyError";
  }
  
  public void sendValidateMessage(String message, HttpServletResponse response)
  {
    try
    {
      response.setCharacterEncoding("utf-8");
      response.getWriter().write(message);
    }
    catch (Exception e) {}
  }
  
  @RequestMapping({"/course/{uuid}"})
  @ResponseBody
  public Map<String, Object> course( @ModelAttribute("page") PageEntity page, QueryTrxorder queryTrxorder, @PathVariable("uuid") Long uuid) {
	  Map dataMap = new LinkedHashMap<String,Object>();
	  try {
		  page.setPageSize(6);
          page.setCurrentPage(1);
          queryTrxorder.setUserId(uuid);
          queryTrxorder.setSellType("LIVE");
          List liveCourse = this.trxorderService.queryOrderForWebUc(queryTrxorder, page);          
          queryTrxorder.setSellType("NOLIVE");
          List noliveCourse = this.trxorderService.queryOrderForWebUc(queryTrxorder, page);
    	  dataMap.put("liveCourse",liveCourse);
    	  dataMap.put("noliveCourse",noliveCourse);
          return SystemUtil.buildResultMap(0,dataMap,"success");
      } catch (Exception var4) {
          logger.error("course", var4);
          return SystemUtil.buildResultMap(1,dataMap,"系统异常");
      }
      
  }
  
  @RequestMapping({"/couselist/{id}"})
  @ResponseBody
  public Map<String, Object> couinfo(Model model, HttpServletRequest request, @PathVariable("id") String id, RedirectAttributes redirectAttributes) {
	  Map dataMap = new LinkedHashMap<String,Object>();
      try {
    	  List kpoint = userKuaijiDaoService.getCourseKpoint(id);
          dataMap.put("videolist", kpoint);         
          return SystemUtil.buildResultMap(0,dataMap,"success");
          
      } catch (Exception var15) {
          logger.error("CourseController.couinfo", var15);
          return SystemUtil.buildResultMap(1,dataMap,"系统异常");
      }

     
  }
  
  @RequestMapping({"/dologin"})
  @ResponseBody
  public Map<String, Object> dologin(@ModelAttribute("userForm") UserForm userForm, HttpServletRequest request, HttpServletResponse response)
  {
    Map dataMap = new LinkedHashMap<String,Object>();
    try
    {
      Map<String, Object> map = getLoginAndRegKeyword();
      if ((ObjectUtils.isNull(map)) || (map.get("verifyLogin").toString().equalsIgnoreCase("OFF"))) {
         return SystemUtil.buildResultMap(1, dataMap, "参数输入异常");
      }
      if (PreventInfusion.sql_inj(userForm.getPassword())) {
        return SystemUtil.buildResultMap(1, dataMap, "参数输入异常");
      }
      
      request.getParameter("test");
      User user = new User();
      user.setEmail(userForm.getEmail().toLowerCase());
      List<User> list = null;
      

      String regEx = "^1{1}[0-9]{10}$";
      Pattern pat = Pattern.compile(regEx);
      Matcher mat = pat.matcher(user.getEmail());
      boolean rs = mat.find();
      if (rs) {
        list = this.userService.getUserListForTelLogin(user);
      }
      Pattern emailRes = Pattern.compile("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
      mat = emailRes.matcher(user.getEmail());
      boolean emailF = mat.matches();
      if (emailF) {
        list = this.userService.getUserListForLogin(user);
      }
      if (ObjectUtils.isNull(list)) {
        return SystemUtil.buildResultMap(1, dataMap, "邮箱格式有误");
      }
      user = (User)list.get(0);



      if (checkIsRight(user.getPassword(), userForm.getPassword(), user.getCustomerkey()))
      {
        String autoThirty = request.getParameter("autoThirty");
        this.userService.setLoginStatus(user, autoThirty, request, response);
        dataMap.put("uid", user.getId());
        return SystemUtil.buildResultMap(0,dataMap,"success");
      }
       else{
        return SystemUtil.buildResultMap(1,dataMap,"密码错误");
      }
    }
    catch (Exception e)
    {
      this.logger.error("Usercontroller.dologin", e);
      return SystemUtil.buildResultMap(1,dataMap,"系统异常");
    }

  }
  
  
  
  @RequestMapping({"/doregister"})
  @ResponseBody
  public Map<String, Object> doregister(@ModelAttribute("userForm") UserForm userForm, ModelMap model, HttpServletRequest request, HttpServletResponse response)
  {
    Map<String, Object> json = null;
    try
    {
      Map<String, Object> map = getLoginAndRegKeyword();
      if ((ObjectUtils.isNull(map)) || (map.get("verifyRegister").toString().equalsIgnoreCase("OFF"))) {
        return getJsonMap(false, "", null);
      }
      if (((ObjectUtils.isNull(map)) || (StringUtils.isEmpty(map.toString()))) && 
        (ObjectUtils.isNull(userForm))) {
        return getJsonMap(false, "formDataIsNot", null);
      }
      String randomCode = request.getParameter("randomCode");
      if ((StringUtils.isEmpty(randomCode)) || (this.memCache.get(MemConstans.MOBILE_REGISTER_CODE + userForm.getMobile()) == null) || (!randomCode.equals(this.memCache.get(MemConstans.MOBILE_REGISTER_CODE + userForm.getMobile())))) {
        return getJsonMap(false, "mobileCodeError", null);
      }
      if ((ObjectUtils.isNull(userForm.getEmail())) || (StringUtils.isEmpty(userForm.getEmail()))) {
        return getJsonMap(false, "emailIsNot", null);
      }
      if ((ObjectUtils.isNotNull(userForm.getEmail())) && (StringUtils.isNotEmpty(userForm.getEmail())))
      {
        Pattern emailRes = Pattern.compile("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
        Matcher mat = emailRes.matcher(userForm.getEmail().toLowerCase());
        boolean emailF = mat.matches();
        if (!emailF) {
          return getJsonMap(false, "emailFormatError", null);
        }
      }
      if ((ObjectUtils.isNull(userForm.getPassword())) || (StringUtils.isEmpty(userForm.getPassword()))) {
        return getJsonMap(false, "pwdIsNull", null);
      }
      if (!userForm.getPassword().equals(userForm.getConfirmPassword())) {
        return getJsonMap(false, "pwdNotEqual", null);
      }
      if ((ObjectUtils.isNull(userForm.getMobile())) || (StringUtils.isEmpty(userForm.getMobile()))) {
        return getJsonMap(false, "mobileIsNull", null);
      }
      if ((ObjectUtils.isNotNull(userForm.getMobile())) && (StringUtils.isNotEmpty(userForm.getMobile())) && (!userForm.getMobile().matches("^(13[0-9]|15[012356789]|18[012356789]|14[57]|17[012356789])[0-9]{8}$"))) {
        return getJsonMap(false, "mobileError", null);
      }
      if (PreventInfusion.sql_inj(userForm.getPassword())) {
        return getJsonMap(false, "regDangerWord", null);
      }
      User user = new User();
      user.setEmail(userForm.getEmail().toLowerCase());
      user.setMobile(userForm.getMobile());
      List<User> list = this.userService.getUserList(user);
      if (ObjectUtils.isNotNull(list)) {
        return getJsonMap(false, "regEmailExist", null);
      }
      int ismobile = this.userService.getUserByMobile(user).intValue();
      if (ismobile != 0) {
        return getJsonMap(false, "regMobileExist", null);
      }
      request.getSession().removeAttribute("COMMON_RAND_CODE");
      
      String userIp = WebUtils.getIpAddr(request);
      user.setMobile(userForm.getMobile());
      user.setPassword(userForm.getPassword());
      user.setUserip(userIp);
      user.setRegisterFrom(UserExpandFrom.registerFrom.toString());
      this.userService.addUser(user);
      Long upUserId = getUpLoginId(request);
      if (upUserId.longValue() != 0L) {
        this.userIntegralService.addUserIntegral(IntegralKeyword.rebate.toString(), upUserId, Long.valueOf(0L), user.getId(), "");
      }
      this.userIntegralService.addUserIntegral(IntegralKeyword.register.toString(), user.getId(), Long.valueOf(0L), Long.valueOf(0L), "");
      
      Map<String, Object> websitemap = this.websiteProfileService.getWebsiteProfileByType(WebSiteProfileType.web.toString());
      Map<String, Object> web = (Map)websitemap.get("web");
      String company = web.get("company").toString();
      
      String conent = "欢迎来到" + company + ",希望您能够快乐的学习";
      this.msgReceiveService.addSystemMessageByCusId(conent, user.getId());
      
      this.userService.setLoginStatus(user, "true", request, response);
      json = getJsonMap(true, "", null);
    }
    catch (Exception e)
    {
      this.logger.error("userRegist error", e);
      json = getJsonMap(false, "系统错误", null);
    }
    return json;
  }
  
  
  
  @RequestMapping({"/checkEmail"})
  public Map<String, Object> checkEmail(@ModelAttribute("userForm") UserForm userForm, HttpServletRequest request, HttpServletResponse response)
  {
    Map<String, Object> json = null;
    try
    {
      if (ObjectUtils.isNotNull(userForm))
      {
        User user = new User();
        user.setEmail(userForm.getEmail().toLowerCase());
        List<User> list = this.userService.getUserList(user);
        if ((ObjectUtils.isNotNull(list)) && (list.size() > 0)) {
          sendValidateMessage("false", response);
        } else {
          sendValidateMessage("true", response);
        }
      }
    }
    catch (Exception e)
    {
      this.logger.error("UserController.checkEmail", e);
      json = getJsonMap(false, "", null);
    }
    return null;
  }
  
  @RequestMapping({"/checkRandomCode"})
  public void checkRandomCode(@RequestParam("randomCode") String randomCode, HttpServletRequest request, HttpServletResponse response)
  {
    try
    {
      if ((ObjectUtils.isNull(randomCode)) || (!randomCode.toUpperCase().equals(request.getSession().getAttribute("COMMON_RAND_CODE")))) {
        sendValidateMessage("false", response);
      } else {
        sendValidateMessage("true", response);
      }
    }
    catch (Exception e)
    {
      this.logger.error("CustomerWebAction.checkRandomCode", e);
    }
  }
  
  @RequestMapping({"/checkRegMoblie"})
  public String checkRegMoblie(@RequestParam("mobile") String mobile, HttpServletRequest request, HttpServletResponse response)
  {
    try
    {
      if (StringUtils.isNotEmpty(mobile))
      {
        User user = new User();
        user.setMobile(mobile);
        if (this.userService.getUserByMobile(user).intValue() != 0) {
          sendValidateMessage("false", response);
        } else {
          sendValidateMessage("true", response);
        }
      }
    }
    catch (Exception e)
    {
      setExceptionRequest(request, e);
      return "/common/error";
    }
    return null;
  }
  
  @RequestMapping({"/user/updatePwd"})
  @ResponseBody
  public Map<String, Object> updatePwd(HttpServletRequest request, HttpServletResponse response, @RequestParam(required=true) String password, @RequestParam(required=true) String confirmPwd, @RequestParam(required=true) String code)
  {
    Map<String, Object> json = null;
    try
    {
      UserCode userCode = this.userCodeService.checkUserCode(code);
      if (ObjectUtils.isNull(userCode)) {
        return getJsonMap(false, "该链接已经使用或者已经过期", null);
      }
      if (password.equals(confirmPwd))
      {
        if (password.length() < 6) {
          return getJsonMap(false, "密码长度不能小于6位", null);
        }
        User user = new User();
        user.setId(userCode.getUserId());
        user.setPassword(password);
        this.userService.updatePwdById(user, userCode);
        json = getJsonMap(true, "", null);
        this.memCache.remove(MemConstans.USEREXPAND_INFO + userCode.getUserId());
      }
      else
      {
        json = getJsonMap(false, "两次密码不一致", null);
      }
    }
    catch (Exception e)
    {
      setExceptionRequest(request, e);
      json = getJsonMap(false, "系统异常", null);
    }
    return json;
  }
  
  @RequestMapping({"/exit"})
  public String exit(HttpServletRequest request, HttpServletResponse response)
  {
    try
    {
      String mobileFlag = request.getParameter("mobileFlag");
      Long userId = SingletonLoginUtils.getLoginUserId(request);
      this.loginOnliceService.deleteLoginOnlineById(userId);
      String sid = WebUtils.getCookie(request, "sid");
      if (StringUtils.isNotEmpty(sid)) {
        this.memCache.remove(sid);
      }
      this.memCache.remove(MemConstans.USEREXPAND_INFO + userId);
      WebUtils.deleteCookie(request, response, "sid");
      WebUtils.deleteCookie(request, response, "sname");
      WebUtils.deleteCookie(request, response, "usercookieuserimg");
      WebUtils.deleteCookie(request, response, "e.subject");
      if ((mobileFlag != null) && (mobileFlag.equals("mobile"))) {
        return "redirect:/mobile/index";
      }
      return "redirect:/index";
    }
    catch (Exception e)
    {
      this.logger.error("UserController.exit", e);
      return setExceptionRequest(request, e);
    }
  }
  
  @RequestMapping({"/user/loginuser"})
  @ResponseBody
  public Object loginuser(HttpServletRequest request)
  {
	
    Map<String, Object> json = null;
    try
    {
      JsonObject userJsonObject = SingletonLoginUtils.getLoginUser(request);
      if (ObjectUtils.isNotNull(userJsonObject))
      {
        userJsonObject.addProperty("password", "");
        userJsonObject.addProperty("customerkey", "");
        json = getJsonMap(true, null, userJsonObject);
      }
      else
      {
        json = getJsonMap(false, null, null);
      }
    }
    catch (Exception e)
    {
      this.logger.error("UserController.exit", e);
      json = getJsonMap(false, "", null);
    }
    return json;
  }
  
  @RequestMapping({"/user/forgetpwd"})
  @ResponseBody
  public Object forgetpwd(HttpServletRequest request, String email, String randomCode, String mobile)
  {
    Map<String, Object> json = null;
    try
    {
      if (StringUtils.isNotEmpty(randomCode))
      {
        if (!randomCode.equals(request.getSession().getAttribute("COMMON_RAND_CODE"))) {
          return getJsonMap(false, "验证码错误", null);
        }
      }
      else {
        return getJsonMap(false, "验证码不能为空", null);
      }
      if (StringUtils.isNotEmpty(email))
      {
        List<String> emails = new ArrayList();
        emails.add(email);
        List<User> userliList = this.userService.getUserIsExsitByEmail(emails);
        if (ObjectUtils.isNotNull(userliList))
        {
          User user = (User)userliList.get(0);
          UserCode userCode = new UserCode();
          userCode.setType(Long.valueOf(0L));
          userCode.setContext(user.getEmail());
          userCode.setUserId(user.getId());
          userCode = this.userCodeService.addUserCode(userCode);
          if (ObjectUtils.isNotNull(userCode))
          {
            String str = gson.toJson(userCode);
            String desCode = PurseSecurityUtils.secrect(str, CommonConstants.SecurityKey);
            String link = CommonConstants.contextPath + "/front/getpwdcode?code=" + URLEncoder.encode(desCode, "utf-8");
            
            Map<String, Object> websitemap = this.websiteProfileService.getWebsiteProfileByType(WebSiteProfileType.web.toString());
            Map<String, Object> web = (Map)websitemap.get("web");
            String company = web.get("company").toString();
            this.emailService.sendMail(userCode.getContext(), "您好,请打开下面的链接并及时修改密码,3天内有效，<a href='" + link + "'>" + link + "</a><br/>如果无法打开，请复制链接到浏览器地址栏中", "帐号找回[" + company + "]");
            
            json = getJsonMap(true, "邮件发送成功", null);
          }
          else
          {
            json = getJsonMap(false, "发送邮件错误,请稍后再试", null);
          }
        }
        else
        {
          json = getJsonMap(false, "该帐号不存在", null);
        }
      }
    }
    catch (Exception e)
    {
      this.logger.error("UserController.exit", e);
      json = getJsonMap(false, "", null);
    }
    return json;
  }
  
  @RequestMapping({"/front/getpwdcode"})
  public Object getpwdcode(HttpServletRequest request, String code)
  {
    try
    {
      UserCode userCode = this.userCodeService.checkUserCode(code);
      if (ObjectUtils.isNull(userCode))
      {
        request.setAttribute("msg", "该链接已经使用或者已经过期");
        return "/common/frontmsg";
      }
    }
    catch (Exception e)
    {
      setExceptionRequest(request, e);
      request.setAttribute("msg", "系统异常");
      return "/common/frontmsg";
    }
    request.setAttribute("code", code);
    return this.getpwdjsp;
  }
  
  public boolean checkIsRight(String dbPassword, String userPassword, String userkey)
  {
    String despassword = PurseSecurityUtils.secrect(userPassword, userkey);
    return despassword.equals(dbPassword);
  }
  
  @RequestMapping({"/front/success"})
  public String gosuccess(Model model, HttpServletRequest request)
  {
    model.addAttribute("msg", WebUtils.replaceTagHTML(request.getParameter("msg")));
    if (request.getParameter("type") != null) {
      model.addAttribute("type", WebUtils.replaceTagHTML(request.getParameter("type")));
    }
    return "/common/msg_success";
  }
  
  @RequestMapping({"/uc/home"})
  public String ucenter(Model model, HttpServletRequest request)
  {
    try
    {
      List<CourseDto> freecourses = this.courseService.getFreeCourseList(getLoginUserId(request), Long.valueOf(6L));
      
      List<CourseDto> courseDtos = this.courseService.getUserBuyCourseList(getLoginUserId(request));
      
      courseDtos = this.courseService.filtrationLive(courseDtos);
      
      List<Article> noticeList = this.articleService.queryArticleIndex();
      model.addAttribute("noticeList", noticeList);
      
      Map<String, List<CourseDto>> mapCourseList = this.courseService.getCourseListByHomePage(Long.valueOf(0L));
      
      Map<String, Object> userIntegralMap = this.userIntegralService.getUserIntegralAndLevel(getLoginUserId(request));
      model.addAttribute("buycourses", courseDtos);
      model.addAttribute("freecourses", freecourses);
      model.addAttribute("mapCourseList", mapCourseList);
      model.addAttribute("userIntegralMap", userIntegralMap);
    }
    catch (Exception e)
    {
      return setExceptionRequest(request, e);
    }
    return "redirect:/uc/mylive";
  }
  
  @RequestMapping({"/uc/acc"})
  public ModelAndView perssonAccout(HttpServletRequest request, @ModelAttribute("page") PageEntity page)
  {
    ModelAndView modelAndView = new ModelAndView();
    QueryUserAccounthistory queryUserAccounthistory = new QueryUserAccounthistory();
    modelAndView.setViewName(this.accoutList);
    try
    {
      queryUserAccounthistory.setUserId(getLoginUserId(request));
      UserAccount userAccount = this.userAccountService.getUserAccountByUserId(getLoginUserId(request));
      List<UserAccounthistory> accList = this.userAccounthistoryService.getWebUserAccountHistroyListByCondition(queryUserAccounthistory, page);
      modelAndView.addObject("userAccount", userAccount);
      modelAndView.addObject("accList", accList);
      modelAndView.addObject("page", page);
    }
    catch (Exception e)
    {
      e.printStackTrace();
      return new ModelAndView(setExceptionRequest(request, e));
    }
    return modelAndView;
  }
  
  @RequestMapping({"/uc/member"})
  public ModelAndView perssonMember(HttpServletRequest request)
  {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName(this.memberInfo);
    try
    {
      List<MemberRecordDTO> memberRecords = this.memberRecordService.getMemberRecordByUser(getLoginUserId(request));
      modelAndView.addObject("memberRecords", memberRecords);
    }
    catch (Exception e)
    {
      this.logger.error("UserController.perssonMember", e);
      return new ModelAndView(setExceptionRequest(request, e));
    }
    return modelAndView;
  }
  
  @RequestMapping({"/uc/uppwd"})
  public String toPwd(HttpServletRequest request)
  {
    return this.toPwd;
  }
  
  @RequestMapping({"/uc/user/updatepwd"})
  @ResponseBody
  public Object updatepwd(HttpServletRequest request, @RequestParam("newpwd") String newpwd, @RequestParam("oldpwd") String oldpwd)
  {
    Map<String, Object> json = null;
    try
    {
      User user = this.userService.getUserById(getLoginUserId(request));
      if (checkIsRight(user.getPassword(), oldpwd, user.getCustomerkey()))
      {
        user.setPassword(newpwd);
        this.userService.updatePwdById(user, null);
        json = getJsonMap(true, "", "");
      }
      return getJsonMap(false, "", null);
    }
    catch (Exception e)
    {
      this.logger.error("UserController.updatepwd", e);
      json = getJsonMap(false, "", null);
    }
    return json;
  }
  
  @RequestMapping({"/uc/uinfo"})
  public String userInfo(HttpServletRequest request)
  {
    try
    {
      UserExpandDto userExpandDto = this.userExpandService.getUserExpandByUids(getLoginUserId(request));
      request.setAttribute("queryUser", userExpandDto);
      List<UserProfile> profileList = this.userProfileService.getUserProfileByUserId(userExpandDto.getCusId());
      if ((profileList != null) && (profileList.size() > 0))
      {
        UserProfile profile = (UserProfile)profileList.get(0);
        request.setAttribute("profile", profile);
      }
    }
    catch (Exception e)
    {
      this.logger.error("UserController.updatepwd", e);
      return setExceptionRequest(request, e);
    }
    return this.userInfo;
  }
  
  @RequestMapping({"/uc/user/update"})
  @ResponseBody
  public Object userUpdateInfo(HttpServletRequest request, @ModelAttribute("queryUser") UserExpandDto queryUser)
  {
    Map<String, Object> json = null;
    try
    {
      queryUser.setId(getLoginUserId(request));
      
      Pattern emailRes = Pattern.compile("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
      Matcher mat = emailRes.matcher(queryUser.getEmail());
      boolean emailF = mat.matches();
      if (!emailF) {
        return getJsonMap(true, "", "emailFormatError");
      }
      List<UserProfile> profileList = this.userProfileService.getUserProfileByUserId(getLoginUserId(request));
      if ((profileList != null) && (profileList.size() > 0))
      {
        queryUser.setUpdateEmail("YES");
        User user = new User();
        user.setEmail(queryUser.getEmail());
        List<User> list = this.userService.getUserList(user);
        if ((list != null) && (list.size() > 0))
        {
          user = (User)list.get(0);
          if ((user.getEmail().equals(queryUser.getEmail())) && (user.getId().longValue() != queryUser.getId().longValue())) {
            return getJsonMap(true, "", "emailHave");
          }
        }
      }
      String falg = this.userService.updateQueryUser(queryUser);
      if ("success".equals(falg))
      {
        JsonObject userJsonObject = SingletonLoginUtils.getLoginUser(request);
        userJsonObject.addProperty("nickname", queryUser.getNickname());
        userJsonObject.addProperty("showname", queryUser.getNickname());
        String sid = WebUtils.getCookie(request, "sid");
        this.memCache.set(sid, userJsonObject.toString(), MemConstans.USER_TIME);
      }
      json = getJsonMap(true, "", falg);
    }
    catch (Exception e)
    {
      this.logger.error("UserController.updatepwd", e);
      json = getJsonMap(false, "", "");
    }
    return json;
  }
  
  @RequestMapping({"/uc/avatar"})
  public String toUserUpdateAvatar(HttpServletRequest request)
  {
    try
    {
      UserExpandDto userExpandDto = this.userExpandService.getUserExpandByUids(getLoginUserId(request));
      request.setAttribute("queryUser", userExpandDto);
    }
    catch (Exception e)
    {
      this.logger.error("UserController.userUpdateAvatar", e);
      return setExceptionRequest(request, e);
    }
    return this.avatar;
  }
  
  @RequestMapping({"/uc/user/updateavatar"})
  @ResponseBody
  public Object userUpdateAvatar(HttpServletRequest request, @RequestParam("userId") Long userId, @RequestParam("avatar") String avatar)
  {
    Map<String, Object> json = null;
    try
    {
      UserExpand userExpand = new UserExpand();
      userExpand.setAvatar(avatar);
      userExpand.setCusId(userId);
      this.userExpandService.updateUserExpand(userExpand);
      
      JsonObject userJsonObject = SingletonLoginUtils.getLoginUser(request);
      userJsonObject.addProperty("avatar", avatar);
      String sid = WebUtils.getCookie(request, "sid");
      this.memCache.set(sid, userJsonObject.toString(), MemConstans.USER_TIME);
      
      json = getJsonMap(true, "", "");
    }
    catch (Exception e)
    {
      this.logger.error("UserController.userUpdateAvatar", e);
      json = getJsonMap(false, "", "");
    }
    return json;
  }
  
  @RequestMapping({"/islogin"})
  @ResponseBody
  public Map<String, Object> isuserLogin(HttpServletRequest request)
  {
    Map<String, Object> json = null;
    if (isLogin(request)) {
      json = getJsonMap(true, null, null);
    }
    return json;
  }
  
  @RequestMapping({"/uc/usercover"})
  @ResponseBody
  public Map<String, Object> getUserPersonalityImages(HttpServletRequest request, @ModelAttribute("page") PageEntity page)
  {
    Map<String, Object> json = null;
    try
    {
      page.setPageSize(12);
      WebsiteImages websiteImages = new WebsiteImages();
      websiteImages.setKeyWord(ImagesType.userPersonalityImages.toString());
      
      List<WebsiteImages> websiteImagesList = this.websiteImagesService.getImgPageList(websiteImages, page);
      Map<String, Object> map = new HashMap();
      map.put("websiteImagesList", websiteImagesList);
      map.put("page", page);
      json = getJsonMap(true, "success", map);
    }
    catch (Exception e)
    {
      this.logger.error("UserController.getUserPersonalityImages", e);
      json = getJsonMap(false, "Images is error", null);
    }
    return json;
  }
  
  @RequestMapping({"/uc/updateusercover"})
  @ResponseBody
  public Map<String, Object> updateUserCover(HttpServletRequest request, @RequestParam("bannerUrl") String bannerUrl)
  {
    Map<String, Object> json = null;
    try
    {
      if (bannerUrl != null)
      {
        this.userExpandService.updateUserExpandBannerUrl(getLoginUserId(request), bannerUrl);
        json = getJsonMap(true, " 更新封面成功", bannerUrl);
      }
      else
      {
        json = getJsonMap(false, " request parameter is null", null);
      }
    }
    catch (Exception e)
    {
      this.logger.error("", e);
      json = getJsonMap(false, "updated is error", null);
    }
    return json;
  }
  
  @RequestMapping({"/letter/delLetterInbox"})
  @ResponseBody
  public Map<String, Object> delLetterInbox(@ModelAttribute MsgReceive msgReceive, HttpServletRequest request)
  {
    Map<String, Object> map = new HashMap();
    try
    {
      msgReceive.setReceivingCusId(getLoginUserId(request));
      Long num = this.msgReceiveService.delMsgReceiveInbox(msgReceive);
      if (num.intValue() == 1) {
        map.put("message", SnsConstants.SUCCESS);
      } else {
        map.put("message", SnsConstants.FALSE);
      }
    }
    catch (Exception e)
    {
      this.logger.error("LetterAction.delLetterInbox", e);
      setExceptionRequest(request, e);
    }
    return map;
  }
  
  @RequestMapping({"/uc/letter"})
  public ModelAndView queryUserLetter(HttpServletRequest request, @ModelAttribute("page") PageEntity page)
  {
    ModelAndView modelAndView = new ModelAndView(this.queryUserLetter);
    try
    {
      page.setPageSize(6);
      MsgReceive msgReceive = new MsgReceive();
      msgReceive.setReceivingCusId(getLoginUserId(request));
      

      List<QueryMsgReceive> queryLetterList = this.msgReceiveService.queryMsgReceiveByInbox(msgReceive, page);
      modelAndView.addObject("queryLetterList", queryLetterList);
      modelAndView.addObject("page", page);
    }
    catch (Exception e)
    {
      this.logger.error("LetterAction.queryLetterByInbox", e);
      setExceptionRequest(request, e);
      return new ModelAndView("/common/error");
    }
    return modelAndView;
  }
  
  @RequestMapping({"/letter/queryUnReadLetter"})
  @ResponseBody
  public Map<String, Object> queryUnReadLetter(HttpServletRequest request)
  {
    Map<String, Object> map = new HashMap();
    try
    {
      if (getLoginUserId(request).longValue() == 0L) {
        return map;
      }
      Map<String, String> queryletter = this.msgReceiveService.queryUnReadMsgReceiveNumByCusId(getLoginUserId(request));
      map.put("entity", queryletter);
    }
    catch (Exception e)
    {
      this.logger.error("LetterAction.queryUnReadLetter", e);
      setExceptionRequest(request, e);
    }
    return map;
  }
  
  @RequestMapping({"/front/pro"})
  @ResponseBody
  public Object frontpro(@RequestParam String type, @RequestParam(required=false) String key, @RequestParam(required=false) String value)
  {
    Map<String, Object> json = null;
    try
    {
      Map<String, Object> websitemap = this.websiteProfileService.getWebsiteProfileByType(type);
      if ((StringUtils.isNotEmpty(key)) && (StringUtils.isNotEmpty(value)))
      {
        websitemap.put(key, value);
        
        JsonObject jsonObject = jsonParser.parse(gson.toJson(websitemap)).getAsJsonObject();
        if ((ObjectUtils.isNotNull(jsonObject)) && (StringUtils.isNotEmpty(jsonObject.toString())))
        {
          WebsiteProfile websiteProfile = new WebsiteProfile();
          websiteProfile.setType(type);
          websiteProfile.setDesciption(jsonObject.toString());
          this.websiteProfileService.updateWebsiteProfile(websiteProfile);
        }
      }
      json = getJsonMap(true, null, websitemap);
    }
    catch (Exception e) {}
    return json;
  }
  
  public Map<String, Object> getLoginAndRegKeyword()
  {
    Map<String, Object> map = new HashMap();
    try
    {
      Map<String, Object> keywordmap = this.websiteProfileService.getWebsiteProfileByType(WebSiteProfileType.keyword.toString());
      if (ObjectUtils.isNotNull(keywordmap))
      {
        JsonObject jsonObject = jsonParser.parse(gson.toJson(keywordmap.get(WebSiteProfileType.keyword.toString()))).getAsJsonObject();
        if ((ObjectUtils.isNotNull(jsonObject)) && (StringUtils.isNotEmpty(jsonObject.toString())))
        {
          map.put("verifyLogin", jsonObject.get("verifyLogin").getAsString());
          map.put("verifyRegister", jsonObject.get("verifyRegister").getAsString());
        }
      }
    }
    catch (Exception e)
    {
      this.logger.error("getLoginAndRegKeyword", e);
    }
    return map;
  }
  
  @RequestMapping({"/uc/myCouAnswer"})
  public ModelAndView myCouAnswer(HttpServletRequest request, @ModelAttribute("page") PageEntity page)
  {
    ModelAndView model = new ModelAndView(this.toMyCouAnswerQuestion);
    try
    {
      List<AnswerQuestion> answerList = this.answerQuestionService.queryMyCouAnswerQuestionList(getLoginUserId(request), page);
      model.addObject("answerList", answerList);
      model.addObject("page", page);
    }
    catch (Exception e)
    {
      this.logger.error("myAnswer", e);
    }
    return model;
  }
  
  @RequestMapping({"/register/getVerification/{phone}/{randomCode}"})
  @ResponseBody
  public Map<String, Object> getVerification(HttpServletRequest request, @PathVariable("phone") String phone, @PathVariable("randomCode") String randomCode)
  {
    Map<String, Object> json = null;
    try
    {
      if ((StringUtils.isEmpty(randomCode)) || (request.getSession().getAttribute("COMMON_RAND_CODE") == null) || (!randomCode.equalsIgnoreCase(request.getSession().getAttribute("COMMON_RAND_CODE").toString()))) {
        return getJsonMap(false, "验证码错误", null);
      }
      if ((ObjectUtils.isNull(phone)) || (StringUtils.isEmpty(phone))) {
        return getJsonMap(false, "请输入手机号", null);
      }
      if ((ObjectUtils.isNotNull(phone)) && (StringUtils.isNotEmpty(phone)) && (!phone.matches("^(13[0-9]|15[012356789]|18[012356789]|14[57]|17[012356789])[0-9]{8}$"))) {
        return getJsonMap(false, "手机号码格式不正确", null);
      }
      User user = new User();
      user.setMobile(phone);
      int ismobile = this.userService.getUserByMobile(user).intValue();
      
      String randCode = createRandom(6);
      if (ismobile != 0) {
        return getJsonMap(false, "该手机号已经注册", null);
      }
      Map<String, Object> map = getLoginAndRegKeyword();
      if ((ObjectUtils.isNull(map)) || (map.get("verifyRegister").toString().equalsIgnoreCase("OFF"))) {
        return getJsonMap(false, "注册接口已关闭，如有疑问请联系客服。", null);
      }
      this.memCache.set(MemConstans.MOBILE_REGISTER_CODE + phone, randCode, MemConstans.MOBILE_REGISTER_CODE_TIME);
      String contents = "【会计岛】尊敬的用户，您正进行“手机号码验证操作”，请输入动态验证码:" + randCode + "，5分钟内有效";
      
      boolean isOk = MobileMessageSendUtil.sendMobileMessage(phone, contents);
      if (isOk) {
        return getJsonMap(true, "验证码已经发送到" + phone + "手机上，如200秒内未收到，请刷新页面重试！", null);
      }
      return getJsonMap(false, "验证码发送失败,请刷新页面重试", null);
    }
    catch (Exception e)
    {
      this.logger.error("getVerification----error", e);
      json = getJsonMap(false, "系统繁忙", null);
    }
    return json;
  }
  
  private String createRandom(int length)
  {
    Random ran = new Random();
    String str = "";
    for (int i = 0; i < length; i++) {
      str = str + ran.nextInt(9);
    }
    System.out.println(str);
    return str;
  }
}



/* Location:           D:\licai\kuaijidao\web\WEB-INF\lib\demo_web_v25.jar

 * Qualified Name:     com.yizhilu.os.edu.controller.user.UserController

 * JD-Core Version:    0.7.0.1

 */